package com.skysail.common.oauth.auth;

import com.skysail.model.BaseModel;
import com.skysail.model.primary.UserModel;
import com.skysail.repository.primary.UserRepository;
import com.skysail.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 自定义用户认证Service
 * @author wangfan
 * @date 2018-11-08
 */
@Service
public class BaseUserDetailService extends BaseModel implements UserDetailsService {
    private static final Logger log = LoggerFactory.getLogger(BaseUserDetailService.class);

    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        List<UserModel> userModellist = userRepository.findByUserName(username);

        if(userModellist!=null && userModellist.size()>0){
            SysUserAuthentication user = new  SysUserAuthentication();
            List<GrantedAuthority> list = AuthorityUtils.createAuthorityList("admin_role"); //所谓的角色，只是增加ROLE_前缀
            user.setUsername(userModellist.get(0).getUserName());
            user.setPassword("{noop}"+userModellist.get(0).getPassword());
            user.setAuthorities(list);
            user.setAccountNonExpired(true);
            user.setAccountNonLocked(true);
            user.setCredentialsNonExpired(true);
            user.setEnabled(true);
            return user;
        }
        return null;
    }

}